<template>
  <el-drawer
    :model-value="isShowRecharge"
    size="380px"
    @close="closeAll"
    :close-on-click-modal="false"
  >
    <template #header="{}">
      <div class="flex items-center justify-start">
        <div class="flex items-center justify-start flex-1">
          <el-icon @click="returnBack"><ArrowLeftBold /></el-icon>
          <p class="flex-1">{{ drawerTitle }}</p>
        </div>
      </div>
    </template>
    <div class="flex flex-col items-start justify-center p-6 balance">
      <p class="mb-2">{{ $t("卡余额") }}</p>
      <p class="text-2xl">{{ cardInfo.balance }} {{ cardInfo.currency }}</p>
    </div>
    <el-card class="mt-8" v-loading="loading">
      <el-form
        ref="rechargeFormRef"
        label-position="top"
        :model="rechargeForm"
        style="max-width: 600px"
        :rules="rules"
        class="amountForm"
      >
        <el-form-item :label="$t('充值金额')" prop="amount">
          <el-input
            v-model="rechargeForm.amount"
            :placeholder="$t('请输入充值金额')"
            class="customAppendInput"
          >
            <template #append
              ><el-button @click="assignValue">
                {{ $t("全部") }}</el-button
              ></template
            >
          </el-input>
        </el-form-item>
      </el-form>
      <div class="detailRow">
        <span class="rowName">{{ $t("卡账户余额") }}</span>
        <span class="rowValue">
          <!-- {{ coinsInfo[0]?.amount }} {{ coinsInfo[0]?.currency }} -->
          <el-select
            v-model="state.currencyInfo"
            class="customSelect"
            @change="selectBalance"
            v-if="coinsInfo && coinsInfo.length > 1"
          >
            <el-option
              v-for="item in coinsInfo"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <p v-else>
            {{ state.currencyInfo }}
          </p>
        </span>
      </div>
      <div class="detailRow">
        <span class="rowName">{{ $t("汇率") }}</span>
        <span class="rowValue">
          1 {{ cardInfo.currency }} ≈ {{ state.price }}
          {{ state.currency }}
        </span>
      </div>
      <div class="detailRow">
        <span class="rowName"
          >{{ $t("手续费")
          }}{{
            `(${
              rechargeRate ? (rechargeRate * 100).toFixed(0) : 0
            }% + ${rechargeFee} ${cardInfo.currency} )`
          }}</span
        >
        <span class="rowValue">
          {{ feeAmount }}
          {{ state.currency }}</span
        >
      </div>
      <div class="detailRow">
        <span class="rowName">{{ $t("扣除") }}</span>
        <span class="rowValue">{{ resultAmount }} {{ state.currency }}</span>
      </div>
    </el-card>
    <div class="flex items-center justify-center w-full mt-8">
      <el-button
        type="primary"
        @click="confirm(rechargeFormRef)"
        class="w-full submitBtn"
        >{{ $t("确认充值") }}</el-button
      >
    </div>
  </el-drawer>
  <PasswordDialog
    :title="$t('确认充值')"
    :info="{
      label: $t('充值金额'),
      amount: rechargeForm.amount,
      currency: cardInfo?.currency,
    }"
    :dialogVisible="dialogVisible"
    @submitForm="submitForm"
    @close="dialogVisible = false"
  ></PasswordDialog>
  <SetTradeDrawer
    :show="isShowPayPwdDrawer"
    :codeType="isHavePassword == 1 ? 'modify' : 'set'"
    @close="closePayPwdDrawer"
  />
</template>
<script setup>
import { ref, reactive, watch, computed } from "vue";
import { cardTransferIn, getCardTransferIn } from "@/api/card/index";
import { GetNewMerchantInfo } from "@/api/merchant/index";
import { useI18n } from "vue-i18n";
import { ElMessage, ElMessageBox } from "element-plus";
import PasswordDialog from "./passwordDialog.vue";
import { truncateDecimals } from "@/utils/utils";
import SetTradeDrawer from "@/views/settings/components/setPayPasswordDrawer.vue";
const { t } = useI18n();
const props = defineProps({
  isShowRecharge: {
    type: Boolean,
    default: false,
  },
  cardId: {
    type: String,
    default: "",
  },
  assetType: {
    type: String,
    default: "",
  },
  isHavePassword: {
    type: Number,
    default: 0,
  },
});

const rechargeFormRef = ref();
const dialogVisible = ref(false);
const emits = defineEmits(["close", "refreshList", "closeAll"]);
const returnBack = () => {
  emits("close");
};
const closeAll = () => {
  rechargeForm.amount = "";
  rechargeFormRef.value?.resetFields();
  emits("closeAll");
};

const drawerTitle = ref(t("充值"));

const rechargeForm = reactive({
  amount: "",
});
const loading = ref(false);
// const currencyList = ref([]); // 币种

const feeAmount = computed(() => {
  return rechargeRate && rechargeForm.amount
    ? asset_type == "balance"
      ? truncateDecimals(
          rechargeForm.amount * rechargeRate.value * state.price +
            rechargeFee.value * state.price,
          2
        )
      : truncateDecimals(
          rechargeForm.amount * rechargeRate.value * state.price +
            rechargeFee.value * state.price,
          8
        )
    : 0;
});

const resultAmount = computed(() => {
  return rechargeRate.value && rechargeForm.amount
    ? asset_type.value == "balance"
      ? truncateDecimals(
          Number(feeAmount.value) + rechargeForm.amount * state.price,
          2
        )
      : truncateDecimals(
          Number(feeAmount.value) + rechargeForm.amount * state.price,
          8
        )
    : 0;
});

watch(
  () => props.isShowRecharge,
  async (val) => {
    if (val) {
      await getBalanceData();
    }
  }
);

watch(
  () => props.isHavePassword,
  (val) => {
    isHavePassword.value = props.isHavePassword;
  }
);
const isShowPayPwdDrawer = ref(false);
const closePayPwdDrawer = async () => {
  const res = await GetNewMerchantInfo();
  isHavePassword.value = res.is_set_trade_password;
  isShowPayPwdDrawer.value = false;
};

const state = reactive({
  price: "",
  totalPrice: "",
  currencyInfo: {},
  currency: "",
});

// 选择资产
const selectBalance = async (val) => {
  state.currency = val.split(" ")[1] || "";
  const res = coinsInfo.value.find((item) => {
    return item.value.split(" ")[1] == state.currency;
  });
  state.price = res.price;
};

const assignValue = () => {
  rechargeForm.amount = state.currencyInfo.split(" ")[0] || "";
};

// // 获取币种价格
// const getCardPrice = async (currency, isTrue) => {
//   if (cardInfo.currency) {
//     let query = {
//       from_currency: cardInfo.currency, //币种
//       to_currency: currency,
//       to_type: props.asset_type == "balance" ? "currency" : "coin", //根据资产类型判断穿什么字段
//     };
//     try {
//       const { price } = await GetCardsPrice(query);
//       state.price = price;
//       state.currency = state.currencyInfo.split(" ")[1] || ""; // 汇率后方的币种

//       // 初始化进来不校验
//       // if (!isTrue && rechargeForm.amount !== "") {
//       //   createFormRef.value.validateField("total_amount");
//       // }
//       // 总额度*汇率 虚拟资产保留6位小数,货币资产保留2位小数
//       if (rechargeForm.amount !== "") {
//         resultAmount =
//           rechargeRate.value && rechargeForm.amount
//             ? props.assetType == "balance"
//               ? truncateDecimals(
//                   Number(rechargeForm.amount) +
//                     rechargeForm.amount * rechargeRate.value,
//                   2
//                 )
//               : truncateDecimals(
//                   Number(rechargeForm.amount) +
//                     rechargeForm.amount * rechargeRate.value,
//                   8
//                 )
//             : 0;
//         // resultAmount =
//         //   (rechargeForm.amount * state.price) +
//         //     (rechargeForm.amount * rechargeRate.value *
//         //     state.price) || 0;
//       } else {
//         resultAmount = 0;
//       }
//     } catch {
//       loading.value = false;
//     }
//   }
// };

const cardInfo = ref({});
const coinsInfo = ref([]);
const rechargeRate = ref("");
const rechargeFee = ref("");
const asset_type = ref("");

const getBalanceData = async () => {
  loading.value = true;
  const res = await getCardTransferIn({ card_id: props.cardId });
  loading.value = false;
  cardInfo.value = res.card;
  coinsInfo.value = res.asset_list;
  coinsInfo.value = coinsInfo.value.map((item) => {
    return {
      label: item.amount + " " + item.currency,
      value: item.amount + " " + item.currency,
      price: item.price,
    };
  });
  // 默认第一条
  state.currencyInfo = coinsInfo.value[0].label;
  state.currency = state.currencyInfo.split(" ")[1] || ""; // 汇率后方的币种
  rechargeRate.value = res.in_rate;
  rechargeFee.value = res.in_fee;
  asset_type.value = res.asset_type;
  state.price = coinsInfo.value[0]?.price || "";
  // getCardPrice(state.currency);
};

const isHavePassword = ref();

const confirm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (isHavePassword.value == 1) {
        dialogVisible.value = true;
      } else {
        ElMessageBox.confirm(t("您需要先设置交易密码"), {
          confirmButtonText: t("去设置"),
          cancelButtonText: t("取消"),
          center: true,
          customClass: "custom-message-box",
        }).then(() => {
          isShowPayPwdDrawer.value = true;
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const submitForm = async (params) => {
  let query = { ...params };
  query.amount = rechargeForm.amount;
  query.card_id = props.cardId;
  query.asset_currency = state.currency;
  await cardTransferIn(query);
  ElMessage({
    type: "success",
    message: t("充值成功"),
  });
  dialogVisible.value = false;
  emits("close");
};

// 卡额度验证，必须大于1
const checkTotalAmount = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t("请输入充值金额")));
  } else {
    if (value <= 1) {
      return callback(new Error(t("充值金额必须大于1")));
    } else if (resultAmount.value > Number(coinsInfo.value[0]?.amount)) {
      return callback(new Error(`${t("账户余额不足")}`));
    } else {
      callback();
    }
  }
};

const rules = reactive({
  amount: [
    { required: true, message: t("请输入充值金额"), trigger: "blur" },
    { validator: checkTotalAmount, trigger: "blur" },
  ],
});
</script>
<style lang="scss" scoped>
.balance {
  height: 100px;
  background-color: rgba(231, 93, 110, 1);
  border-radius: 10px;
  color: #fff;
}
.submitBtn {
  height: 40px;
  border-radius: 10px;
}
.detailRow {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
}
.exchange-icon {
  border-radius: 50%;
  background-color: #e54c60;
  color: #fff;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  margin-right: 10px;
  .text {
    display: inline-block;
    line-height: 14px;
  }
}
.userSelect .el-select-dropdown__item {
  min-width: 100px !important;
  height: 45px !important;
  //   padding: 0 5px 0 5px !important;
  display: flex;
  justify-content: center;
  flex-direction: column;
}
.userSelect .custom-option {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 3px; /* 这里使用 margin 替代类名 mb-3 */
}

.custom-button {
  background-color: #e54c60 !important;
  border-color: #e54c60 !important;
  color: #fff !important;
}
.custom-button:hover,
.custom-button:focus,
.custom-button:active {
  background-color: #e54c60 !important; /* 点击时的背景色，!important 是为了确保覆盖 Element UI 默认样式 */
  border-color: #e54c60 !important; /* 点击时的边框颜色 */
  color: #fff !important; /* 点击时的文字颜色 */
}
.alertInfo {
  background: #f0f9ff;
  color: #333;
  margin-bottom: 15px;
}
.iconDanger {
  color: #fe5042;
  font-size: 20px;
}
.iconInfo {
  color: #18a6e9;
  font-size: 20px;
}
.info {
  color: #333;
  font-size: 14px;
}
</style>
